import React, { useEffect, useState } from "react";
import Taro from "@tarojs/taro"
import { observer } from "mobx-react";
import { View, Button } from "@tarojs/components";
import { AtCountdown } from 'taro-ui'
import http from '@/request/index';
import user from '@/store/user';
import "./index.scss"

const Home: React.FC = observer(() => {
  const [msg, setMsg] = useState('test')
  const [times, setTimes] = useState(0)
  const [loading, setLoading] = useState(false)
  useEffect(() => {
    setMsg('mobx状态管理演示')
  }, [])

  const useLogin = () => {
    setLoading(true)
    Taro.login({
      success: (data) => {
        http.post('/user/aiLedger/wechatLogin', {
          code: data.code
        }).then(res => {
          setTimes(10)
          user.updateInfo(res.data)
          // Taro.navigateTo({
          //   url: '/pages/home/index'
          // })
        }).finally(() => {
          setLoading(false)
        })
      },
      fail: () => {
        setLoading(false)
      }
    })
  }

  const useUpdate = () => {
    user.updateInfo()
  }

  const toPage = (url) => {
    Taro.navigateTo({url})
  }

  return(
    <View className="page safe-page flex-column">
      <AtCountdown
        format={{ hours: ':', minutes: ':', seconds: '' }}
        seconds={times}>
      </AtCountdown>
      <View className="func-area flex-row flex-warp">
        <Button className="btn" onClick={() => toPage('/pages/demo/ref/index')} size='mini' type='primary'>Ref演示</Button>
        <Button className="btn" onClick={() => toPage('/pages/demo/effect/index')} size='mini' type='primary'>Effect演示</Button>
        <Button className="btn" onClick={() => toPage('/pages/demo/reducer/index')} size='mini' type='primary'>Reducer演示</Button>
        <Button className="btn" onClick={() => toPage('/pages/demo/memo/index')} size='mini' type='primary'>Memo演示</Button>
        <Button className="btn" onClick={() => toPage('/pages/demo/callback/index')} size='mini' type='primary'>useCallback演示</Button>
        <Button className="btn" onClick={() => toPage('/pages/demo/transition/index')} size='mini' type='primary'>transition演示</Button>
        <Button className="btn" onClick={() => Taro.switchTab({url: '/pages/book/index'})} size='mini' type='primary'>记账演示</Button>
        <View className="flex1"></View>
      </View>
      <View>{msg}</View>
      <View className="flex1">{user.info?.userName || '未登录'}</View>
      <View className="flex-row">
        <Button className="flex1" onClick={useLogin} loading={loading} type='primary'>登录</Button>
        <Button className="flex1" onClick={useUpdate} loading={loading} type='primary'>刷新</Button>
      </View>
    </View>
  )
})
export default Home
